<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script src="${basepath}/inc/js/jquery/2.0.0/jquery.min.js"></script>
<link href="${basepath}/inc/css/bootstrap/bootstrap.min.css" rel="stylesheet">
<script src="${basepath}/inc/js/bootstrap/3.3.6/bootstrap.min.js"></script>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=eN9cBjl262LzV7Q0dVAE0dcmNY4yzO6H"></script>
<script type="text/javascript" src="http://api.map.baidu.com/library/TrafficControl/1.4/src/TrafficControl_min.js"></script>
<link href="http://api.map.baidu.com/library/TrafficControl/1.4/src/TrafficControl_min.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<title>浏览器定位</title>
<style type="text/css">
body, html, #allmap {
	width: 100%;
	height: 100%;
	overflow: hidden;
	margin: 0;
	font-family: "微软雅黑";
}
h2{
	margin-top:0px;
	margin-bottom:0px;
}
.navleft{
	margin-left: 20px;
	margin-right: 20px;
	margin-bottom: 0px;
}
.right{
	float:right;
}
a{
	color: black;
}
a:hover{
	text-decoration:none;
	color: black;
}
</style>
</head>
<body>
	<div class="input-group">
		<span class="input-group-addon glyphicon glyphicon-chevron-left"id="return"> </span> 
		<input type="text" class="form-control inputSearch" placeholder="搜索" aria-label="Amount (to the nearest dollar)" id="searchtxt">
			 <span class="input-group-addon btn" id="search">搜索</span>
	</div>
	<div id="allmap"></div>
		<nav class="navbar navbar-default navbar-fixed-bottom navleft">
		<div class="panel panel-default">
			<div class="panel-body " id="information"></div>
		</div>
	</nav>
	<script type="text/javascript">
	// 百度地图API功能
	$(function(){
	var distance=null;
	var myGeo = new BMap.Geocoder();
	var map = new BMap.Map("allmap");
	var point = new BMap.Point(116.331398, 39.897445);
	map.centerAndZoom(point, 14);
	var opts = {type: BMAP_NAVIGATION_CONTROL_SMALL}
	var control=new BMap.NavigationControl(opts);
	var leftControl = document.getElementById("information");
	var geoc = new BMap.Geocoder(); 
	//实时路况
	var ctrl = new BMapLib.TrafficControl({
		showPanel:false
	});
	map.addControl(ctrl);
	ctrl.setAnchor(BMAP_ANCHOR_TOP_LEFT);
	
	control.setAnchor(BMAP_ANCHOR_TOP_RIGHT);	 
	map.addControl(control);
	var geolocation = new BMap.Geolocation();
	//实时定位
	function getLocation(){
	    if (navigator.geolocation){
	        navigator.geolocation.getCurrentPosition(showPosition,showError);
	        var geolocation = new BMap.Geolocation();
        	geolocation.getCurrentPosition(function(r){ 
/*         		var mk = new BMap.Marker(r.point);
    			map.addOverlay(mk);
    			map.panTo(r.point); */
        	},{enableHighAccuracy: true});   	
	    }else{
	        alert("浏览器不支持地理定位。");
	    }
	} 
	 //定位失败处理
	function showError(error){
	    switch(error.code) {
	        case error.PERMISSION_DENIED:
	            alert("定位失败,用户拒绝请求地理定位");
	            break;
	        case error.POSITION_UNAVAILABLE:
	            alert("定位失败,位置信息是不可用");
	            break;
	        case error.TIMEOUT:
	            alert("定位失败,请求获取用户位置超时");
	            break;
	        case error.UNKNOWN_ERROR:
	            alert("定位失败,定位系统失效");
	            break;
	    }
	}

	 //微信sdk
	 wx.getLocation({
    //如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
    success:function(res){
        var latitude=res.latitude;
        var longitude=res.longitude;
        var speed=res.speed;
        var accuracy=res.accuracy;
        alert('经度：'+latitude+'，纬度：'+longitude);
    },
    cancel: function (res) {
        alert('用户拒绝授权获取地理位置');
    }
});
	 
	 
	 $('.inputSearch').focus(function(){
		 $('.navleft').hide();
	 });
	function showPosition(position){
	    var latlon = position.coords.latitude+','+position.coords.longitude;
	    //baidu
	    var url = "http://api.map.baidu.com/geocoder/v2/?ak=eN9cBjl262LzV7Q0dVAE0dcmNY4yzO6H&callback=renderReverse&location="+latlon+"&output=json&pois=0";
	    $.ajax({
	        type: "GET",
	        dataType: "jsonp",
	        url: url,
	        success: function (json) {
	    		//搜索最近的20个停车场
	    		$('#search').click(function(){
	    			var allmap = map.getOverlays();
	    			$('.navleft').hide();
	    		    map.clearOverlays();
	    		    var $search = $('.inputSearch').val();
	    		    //地址转换
	    		    geoc.getPoint($search,function(point){
	    		    	if(point){
	    					map.centerAndZoom(point, 15);
	    					map.addOverlay(new BMap.Marker(point));
	    		    		shortDistance(point);
	    					leftControl.innerHTML = "<div class=\"parkingdiv\"><span ><h2>"+$search+"</h2></span>";

	    		    	}else{
	    		    		alert("周围没有停车场");
	    		    	}
	    		    },json.result.addressComponent.city);
	    		});
	            if(json.status==0){
	            	var jsonString = JSON.stringify(json);
	                var lat = json.result.location.lat;
	                var lng = json.result.location.lng;
	                var point=new BMap.Point(lng,lat);
	                addMarker(point);//添加标注
	                shortDistance(point);//加载最近的20个车场
	            }
	        },
	        error: function (XMLHttpRequest, textStatus, errorThrown) {
	            alert("地址位置获取失败");
	        }
	    });
	}

	// 地图上创建标注
	function addMarker(point){
	  var marker = new BMap.Marker(point);
	  map.addOverlay(marker);
	  map.panTo(point);
	}
	

	//添加最近的20个车场
	function shortDistance(point){
		var myLocation = point;
		$.post('${basepath}/parklot/search.znck',{
			longitude : point.lng,
			Latitude : point.lat
		},function(data,textStatus){	
			var jsonData = eval("("+data+")");
			if(jsonData.length!=0){
				$('.navleft').show();
				}
			if(jsonData.length==0){
				$('.navleft').hide();
			}
			for(var i = 0; i<jsonData.length; i++){
				var dataString = JSON.stringify(jsonData[i]); 
				var marker =new BMap.Point(jsonData[i].longitude,jsonData[i].latitude);
				//addMarker(marker);
				addClickHandler(marker,point,dataString);
			}
		});
	}
	//添加信息窗口,marker是需要标记的地址,point是我的地址
	function addClickHandler(marker,myLocation,data){
		  var jsonData = eval("("+data+")");
		  var marker = new BMap.Marker(marker);
		  map.addOverlay(marker);
		  map.panTo(marker); 
		  marker.addEventListener("click",function(){
	    	//驾车获取时间与距离
	    	var searchComplete = function (results){
	    		if (transit.getStatus() != BMAP_STATUS_SUCCESS){
	    			return ;
	    		}
	    		var plan = results.getPlan(0);
	    		//获取时间	
	    		var time = plan.getDuration(true);    
	    		var distance = plan.getDistance(true);  
	    		geoc.getLocation(myLocation,function(result){
			    	//逆地址转换
				    	var addCom = result.addressComponents;
						var city = addCom.city;
						var address = addCom.province + addCom.city+addCom.district+ addCom.street+addCom.streetNumber;
						leftControl.innerHTML = "<div class=\"parkingdiv\"><a href=\"${basepath}/parklot/profile/"+jsonData.id+".znck\"><span ><h2>"+jsonData.name+"</h2></span>"+
						"<span>空车位"+jsonData.surplus_park_num+"个●起始价"+jsonData.init_price+"元</span><br>"+
						"<span>距离"+distance+"●</span>"+address+"</span></a>"+
						"<span class=\"goHere\"><button type=\"button\" class=\"btn btn-block nav\">"+
						"<span class=\"glyphicon glyphicon-send\"></span>去这里</button></span>";	
						$('.goHere').click(function(){
							    window.location.href="http://api.map.baidu.com/direction?origin=latlng:"+myLocation.lat +","+myLocation.lng+"|name:我的位置&destination=latlng:" 
					    		+ jsonData.latitude + "," + jsonData.longitude + "|name:" + address
					    		+ "&mode=driving&region="+ city +"&output=html&src=yourCompanyName|yourAppName";
							});
			    });
	    	}
	    	var transit = new BMap.DrivingRoute(map, { onSearchComplete: searchComplete });
	    	transit.search(myLocation, marker);
		});
	}
     
	
	function goHere(){
			//逆地址解析
			myGeo.getLocation(point,function(rs){
				var addCom = rs.addressComponents;
				var city = addCom.city;
				var address = addCom.province + addCom.city+addCom.district+ addComp.street+addComp.streetNumber;
			    window.location.href="http://api.map.baidu.com/direction?origin=latlng:"+myLocation.lat +","+myLocation.lng+"|name:我的位置&destination=latlng:" 
	    		+ item.longitude + "," + item.longitude + "|name:" + address
	    		+ "&mode=driving&region="+ city +"&output=html&src=yourCompanyName|yourAppName";
			});
	}
	

	getLocation();
    
	//定位功能
//	geolocation.getCurrentPosition(function(r) {
/* 		if (this.getStatus() == BMAP_STATUS_SUCCESS) {  
			var mk = new BMap.Marker(r.point);
			var myLocation=r.point;
			map.addOverlay(mk);
			map.panTo(r.point);
			mk.enableDragging();
		} else {
			alert('failed' + this.getStatus());
		}
		var leftControl = document.getElementById("information");
		<c:forEach items="${parkinglots}" var="parking" varStatus="status">		
			var point=new BMap.Point("${parking.longitude}","${parking.latitude}");
		    marker["${status.count}"]=new BMap.Marker(point);
		    map.addOverlay(marker["${status.count}"]);
		    marker["${status.count}"].addEventListener("click",function(){
		    	//驾车获取时间与距离
		    	var searchComplete = function (results){
		    		if (transit.getStatus() != BMAP_STATUS_SUCCESS){
		    			return ;
		    		}
		    		var plan = results.getPlan(0);
		    		var time = plan.getDuration(true);                //获取时间	
		    		var distance = plan.getDistance(true);  
		    		
				    myGeo.getLocation(point,function(result){
				    		var addComp = result.addressComponents;
				    	    address=addComp.province+addComp.city+addComp.district+addComp.street+addComp.streetNumber;
					    	leftControl.innerHTML = "<div class=\"parkingdiv\"><a href=\"${basepath}/parklot/profile/${parking.id}.znck\"><span ><h2>${parking.name}</h2></span>"+
							"<span>空车位${parking.surplus_park_num}个●起始价${parking.init_price}元</span><br>"+
							"<span>距离"+distance+"●</span>"+address+"</span></a>"+
							"<span class=\"goHere\"><button type=\"button\" class=\"btn btn-block nav\">"+
							"<span class=\"glyphicon glyphicon-send\"></span>去这里</button></span>";	
							$('.goHere').click(function(){
								//计算时间
								//var searchComplete = function(results){}
								//alert(myLocation);
								//leftControl.innerHTML= null;
								//var map1 = new BMap.Map("allmap");
								//map.centerAndZoom(myLocation, 11);
								//var driving = new BMap.DrivingRoute(map1, 
									//	{renderOptions: {map: map1,panel: "information", autoViewport: true}});
								//driving.search(myLocation,point);
								//逆地址解析
								myGeo.getLocation(point,function(rs){
									var addCom = rs.addressComponents;
									var city = addCom.city;
									var address = addCom.city+addCom.district+ addComp.street+addComp.streetNumber;
								    window.location.href="http://api.map.baidu.com/direction?origin=latlng:"+myLocation.lat +","+myLocation.lng+"|name:我的位置&destination=latlng:" 
						    		+ "${parking.latitude}" + "," + "${parking.longitude}" + "|name:" + address
						    		+ "&mode=driving&region="+ city +"&output=html&src=yourCompanyName|yourAppName";
								});
							});
				    });
		    	}
		    	var transit = new BMap.DrivingRoute(map, { onSearchComplete: searchComplete });
		    	transit.search(myLocation, point);
		    });
		</c:forEach>
		//搜索功能
		$('.inputSearch').focus(function(){
			$('.navleft').remove();
			$('parkingdiv').remove();
		});
		$('#search').click(function(){
			var point = new BMap.Point(116.331398, 39.897445);
			map1.centerAndZoom(point, 14);
			var marker1 = [];
			var address= $('.inputSearch').val();
			myGeo.getLocation(myLocation,function(rs){
				var addCom = rs.addressComponents;
				var city = addCom.city;
				// 获取地址
				myGeo.getPoint(address, function(point){
					if (point){
						$.post('${basepath}/parklot/search.znck',{
							longitude : point.lng,
							Latitude : point.lat
						},function(data,textStatus){		
							var jsonData = eval("("+data+")");
							for(var i = 0; i<jsonData.length; i++){
								var item = jsonData[i];
								var point1=new BMap.Point(item.longitude,item.latitude);
								 marker1[i] = new BMap.Marker(point1);	
								 map.addOverlay(marker1[i]);
								 alert(point1);
							}
						});
					}else{
						alert("您选择地址没有解析到结果!");
					}
				}, city);  

			});
		});
	}, {
		enableHighAccuracy : true
	}); */
	});
</script>
</body>
</html>
